package com.weicong.openchat.face;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.weicong.openchat.R;

public class FaceUtil {
	
	private static Context mContext; 
	private static ViewPager mViewPager;
	private static LinearLayout mDotsLayout;
	
	private static int mRows; // 表情行数
	private static int mColumns; // 表情列数
	
	private static List<String> mFaceList;
	private static EditText mMsgText;
	
	// 每一页表情的视图
	private static List<View> mViews;
	
	/**
	 * 初始化表情功能，调用此方法即可增加表情功能
	 * 注意：需要在adapter中判断显示表情
	 * @param context 
	 * @param viewPager ViewPager实例
	 * @param dotsLayout 放置表情下面圆点的位置
	 * @param rows 表情的行数
	 * @param columns 表情的列数
	 * @param msgText 发送消息的输入框（EditText实例）
	 */
	public static void init(Context context, ViewPager viewPager, LinearLayout dotsLayout,
			int rows, int columns, EditText msgText) {
		mContext = context;
		mDotsLayout = dotsLayout;
		mRows = rows;
		mColumns = columns;
		mViewPager = viewPager;
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
			
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			
			}
			
			@Override
			public void onPageSelected(int arg0) {
				for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
					mDotsLayout.getChildAt(i).setSelected(false);
				}
				mDotsLayout.getChildAt(arg0).setSelected(true);
			}

		});
		
		mMsgText = msgText;
		
		initFaceList();
		initViewPager();
	}
	
	private static void initFaceList() {
		try {
			mFaceList = new ArrayList<String>();
			String[] faces = mContext.getAssets().list("face/png");
			//将Assets中的表情名称转为字符串一一添加进staticFacesList
			for (int i = 0; i < faces.length; i++) {
				mFaceList.add(faces[i]);
			}
			//去掉删除图片
			mFaceList.remove("emotion_del_normal.png");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化表情 
	 */
	private static void initViewPager() {
		mViews = new ArrayList<View>();
		// 获取页数
		for (int i = 0; i < getPagerCount(); i++) {
			mViews.add(viewPagerItem(i));
			LayoutParams params = new LayoutParams(16, 16);
			mDotsLayout.addView(dotsItem(i), params);
		}
		FaceVPAdapter mVpAdapter = new FaceVPAdapter(mViews);
		mViewPager.setAdapter(mVpAdapter);
		mDotsLayout.getChildAt(0).setSelected(true);
	}

	private static ImageView dotsItem(int position) {
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.dot_image, null);
		ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
		iv.setId(position);
		return iv;
	}
	
	private static View viewPagerItem(int position) {
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.face_gridview, null); // 表情布局
		GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
		/**
		 * 注：因为每一页末尾都有一个删除图标，所以每一页的实际表情columns *　rows　－　1; 空出最后一个位置给删除图标
		 */
		List<String> subList = new ArrayList<String>();
		subList.addAll(mFaceList.subList(position * (mColumns * mRows - 1),
				(mColumns * mRows - 1) * (position + 1) > mFaceList.size() ? mFaceList.size() 
			    : (mColumns * mRows - 1) * (position + 1)));
		/**
		 * 末尾添加删除图标
		 */
		subList.add("emotion_del_normal.png");
		FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList, mContext);
		gridview.setAdapter(mGvAdapter);
		gridview.setNumColumns(mColumns);
		// 单击表情执行的操作
		gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				try {
					String png = ((TextView) ((LinearLayout) view).getChildAt(1)).getText().toString();
					if (!png.contains("emotion_del_normal")) {// 如果不是删除图标
						insert(getFace(png));
//						chat_face_container.setVisibility(View.GONE);
					} else {
						delete();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		return gridview;
	}
	
	private static SpannableStringBuilder getFace(String png) {
		SpannableStringBuilder sb = new SpannableStringBuilder();
		try {
			/**
			 * 经过测试，虽然这里tempText被替换为png显示，但是但我单击发送按钮时，获取到輸入框的内容是tempText的值而不是png
			 * 所以这里对这个tempText值做特殊处理
			 * 格式：#[face/png/f_static_000.png]#，以方便判斷當前圖片是哪一個
			 */
			String tempText = "#[" + png + "]#";
			sb.append(tempText);
			sb.setSpan(
					new ImageSpan(mContext, BitmapFactory
							.decodeStream(mContext.getAssets().open(png))), sb.length()
							- tempText.length(), sb.length(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return sb;
	}
	
	/**
	 * 向输入框里添加表情
	 */
	private static void insert(CharSequence text) {
		int iCursorStart = Selection.getSelectionStart((mMsgText.getText()));
		int iCursorEnd = Selection.getSelectionEnd((mMsgText.getText()));
		if (iCursorStart != iCursorEnd) {
			((Editable) mMsgText.getText()).replace(iCursorStart, iCursorEnd, "");
		}
		int iCursor = Selection.getSelectionEnd((mMsgText.getText()));
		((Editable) mMsgText.getText()).insert(iCursor, text);
	}
	
	/**
	 * 删除图标执行事件
	 * 注：如果删除的是表情，在删除时实际删除的是tempText即图片占位的字符串，所以必需一次性删除掉tempText，才能将图片删除
	 */
	private static void delete() {
		if (mMsgText.getText().length() != 0) {
			int iCursorEnd = Selection.getSelectionEnd(mMsgText.getText());
			int iCursorStart = Selection.getSelectionStart(mMsgText.getText());
			if (iCursorEnd > 0) {
				if (iCursorEnd == iCursorStart) {
					if (isDeletePng(iCursorEnd)) {
						String st = "#[face/png/f_static_000.png]#";
						((Editable) mMsgText.getText()).delete(
								iCursorEnd - st.length(), iCursorEnd);
					} else {
						((Editable) mMsgText.getText()).delete(iCursorEnd - 1,
								iCursorEnd);
					}
				} else {
					((Editable) mMsgText.getText()).delete(iCursorStart,
							iCursorEnd);
				}
			}
		}
	}
	
	/**
	 * 判断即将删除的字符串是否是图片占位字符串tempText 如果是：则讲删除整个tempText
	 */
	private static boolean isDeletePng(int cursor) {
		String st = "#[face/png/f_static_000.png]#";
		String content = mMsgText.getText().toString().substring(0, cursor);
		if (content.length() >= st.length()) {
			String checkStr = content.substring(content.length() - st.length(),
					content.length());
			String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(checkStr);
			return m.matches();
		}
		return false;
	}
	
	/**
	 * 根据表情数量以及GridView设置的行数和列数计算Pager数量
	 * @return
	 */
	private static int getPagerCount() {
		int count = mFaceList.size();
		return count % (mColumns * mRows - 1) == 0 ? count / (mColumns * mRows - 1)
				: count / (mColumns * mRows - 1) + 1;
	}
	
	/**
	 * 将文本内容content转化为表情显示到textView上
	 * @param context 上下文
	 * @param textView 要显示表情的TextView
	 * @param content 文本内容
	 * @return
	 */
	public static SpannableStringBuilder stringToFace(Context context, final TextView textView, String content) {
		SpannableStringBuilder sb = new SpannableStringBuilder(content);
		String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(content);
		while (m.find()) {
			String tempText = m.group();
			try {
				String num = tempText.substring("#[face/png/f_static_".length(), tempText.length()- ".png]#".length());
				String gif = "face/gif/f" + num + ".gif";
				/**
				 * 如果open这里不抛异常说明存在gif，则显示对应的gif
				 * 否则说明gif找不到，则显示png
				 * */
				InputStream is = context.getAssets().open(gif);
				sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is,new AnimatedGifDrawable.UpdateListener() {
							@Override
							public void update() {
								textView.postInvalidate();
							}
						})), m.start(), m.end(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				is.close();
			} catch (Exception e) {
				String png = tempText.substring("#[".length(),tempText.length() - "]#".length());
				try {
					sb.setSpan(new ImageSpan(context, BitmapFactory.decodeStream(context.getAssets().open(png))), m.start(), m.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}
		return sb;
	}
	
	public static boolean contain(String content) {
		String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(content);
		return m.find();
	}
}
